package com.iteaj.iot.test.server.api;

import com.iteaj.iot.FrameworkManager;
import com.iteaj.iot.IotThreadManager;
import com.iteaj.iot.server.ServerProtocolHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.iteaj.iot.test.TestConst.LOGGER_API_DESC;

@Component
public class ApiServerStopTestProtocolHandle implements ServerProtocolHandle<ApiServerStopTestProtocol> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Object handle(ApiServerStopTestProtocol protocol) {
        IotThreadManager.instance().getExecutorService().schedule(() -> {
            boolean stop = FrameworkManager.stop(ApiTestServerMessage.class);
            if(stop) {
                logger.info(LOGGER_API_DESC, "FrameworkManager", "stop", "通过");
                IotThreadManager.instance().getExecutorService().schedule(() -> {
                    try {
                        FrameworkManager.start(ApiTestServerMessage.class);

                        // 注册关闭api的协议handle
                        FrameworkManager.register(new ApiServerCloseTestProtocolHandle());
                        logger.info(LOGGER_API_DESC, "FrameworkManager", "start", "通过");
                    } catch (Exception e) {
                        logger.error(LOGGER_API_DESC, "FrameworkManager", "start", "失败");
                    }
                },1, TimeUnit.SECONDS);
            } else {
                logger.error(LOGGER_API_DESC, "FrameworkManager", "stop", "失败");
            }
        }, 2, TimeUnit.SECONDS);

        return null;
    }
}
